package xiaolong.lian.util;


import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Cookies {
    private static final int defaultMaxAge = 30*24*60*60;
    public static void addOne(String name, String value, int maxAge, boolean httpOnly){
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(maxAge);
        cookie.setHttpOnly(httpOnly);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    public static void addOne(String name, String value, int maxAge){
        addOne(name, value, maxAge, false);
    }

    public static void addOne(String name, String value){
        addOne(name, value, defaultMaxAge, false);
    }

    public static String get(String key){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Object value = request.getAttribute(key);
        if(value != null)
            return value.toString();

        LoggerFactory.getLogger(Cookies.class).debug("从cookie中查找");
        Cookie[] cookies = request.getCookies();
        for(Cookie cookie : cookies){
            if(cookie.getName().equals(key))
                return cookie.getValue();
        }
        return "";
    }
}
